import time
import random
from concurrent.futures import ThreadPoolExecutor, as_completed


def slow_operation(task_id):
    """模拟一个耗时的网络请求"""
    sleep_time = random.uniform(0.5, 2)
    time.sleep(sleep_time)
    return f"Task {task_id} completed in {sleep_time:.2f} seconds"


def process_concurrent():
    start = time.perf_counter()
    results = []

    # 创建线程池，设置最大线程数为4
    with ThreadPoolExecutor(max_workers=4) as executor:
        # 提交任务到线程池
        future_to_id = {executor.submit(slow_operation, i): i for i in range(10)}

        # 获取结果
        for future in as_completed(future_to_id):
            results.append(future.result())

    end = time.perf_counter()
    print(f"concurrent.futures 处理总耗时：{end - start:.2f} 秒")
    return results


if __name__ == "__main__":
    process_concurrent()
